package com.gitee.baqkft.code.core.db;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import com.gitee.baqkft.code.core.handler.AbstractGenHandler;
import com.gitee.baqkft.code.core.handler.GenSQLHandler;
import com.gitee.baqkft.code.core.util.FreemarkerUtils;
import com.gitee.baqkft.code.core.util.StringUtils;
import com.gitee.baqkft.code.db.DBTable;

import freemarker.template.Template;

/**
 * SQL程序处理器
 * @author chenmingcai
 * @date 2018年6月4日 下午2:41:19 
 *
 */

public class SQLHandler extends AbstractGenHandler implements GenSQLHandler
{
	private static GenSQLHandler handler;
	
	/**
	 * 获取处理器
	 * @return
	 */
	public static GenSQLHandler getHandler()
	{
		if(handler == null)
		{
			handler = new SQLHandler();
		}
		return handler;
	}
	
	private SQLHandler()
	{
		freemarkerConfig.setClassLoaderForTemplateLoading(Thread.currentThread().getContextClassLoader(), "template/sql");
	}

	@Override
	public String select(DBTable table)
	{
		return process(table, "select.ftl");
	}

	@Override
	public String update(DBTable table)
	{
		return process(table, "update.ftl");
	}

	@Override
	public String insert(DBTable table)
	{
		return process(table, "insert.ftl");
	}
	
	/**
	 * 处理数据
	 * @param table
	 * @param templ
	 * @return
	 */
	private String process(DBTable table, String templ)
	{
		StringWriter writer = new StringWriter();
		try
		{
			Template tmpl = FreemarkerUtils.loadTemplate(freemarkerConfig, templ);
			Map<String, Object> model = new HashMap<String, Object>();
			model.put("table", table);
			model.put("handler", this);
			tmpl.process(model, writer);
		}
		catch(Exception ex)
		{
			logger.error("模板处理失败", ex);
		}
		return writer.toString();
	}
	
	/**
	 * 转换成驼峰命名法
	 * @param text
	 * @return
	 */
	public String toCamelString(String text)
	{
		return StringUtils.toCamelString(text);
	}
}
